package com.itheima.d5_tcp2;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;

public class MyThread extends Thread {
    private Socket socket;

    public MyThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //3.接收输入流对象

//        BufferedInputStream bis = null;
        try {
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            while (true) {
                String s = null;
                try {
                    byte[] bytes = new byte[1024];
                    int len;
                    try {
                        if (!((len = bis.read(bytes)) != -1)) break;
                    } catch (IOException e) {
                        throw new RuntimeException(e);

                    }

                    s = new String(bytes, 0, len);
                } catch (Exception e) {
                    System.out.println("客户端下线了..."+socket.getInetAddress().getHostAddress());
                    bis.close();
                    socket.close();
                    break;
                }
                System.out.println("服务器收到的信息:");
                System.out.println(s);
                System.out.println("对方的IP地址:" + socket.getInetAddress().getHostAddress());
                System.out.println("对方的端口号:" + socket.getPort());
                System.out.println("================================");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
